<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目管理 - 学术研究自动化系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background: #f5f7fa;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            text-align: center;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            background: white;
            padding: 1rem 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .btn {
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: background 0.3s ease;
        }
        
        .btn:hover {
            background: #5a6fd8;
        }
        
        .btn-success {
            background: #28a745;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .projects-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 2rem;
        }
        
        .project-card {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .project-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .project-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }
        
        .project-title {
            font-size: 1.2rem;
            font-weight: bold;
            color: #333;
            margin-bottom: 0.5rem;
        }
        
        .project-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        
        .status-planning {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-completed {
            background: #cce5ff;
            color: #004085;
        }
        
        .project-description {
            color: #666;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }
        
        .project-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            font-size: 0.8rem;
            color: #888;
        }
        
        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 1rem;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            transition: width 0.3s ease;
        }
        
        .project-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .btn-small {
            padding: 6px 12px;
            font-size: 0.8rem;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }
        
        .close {
            font-size: 2rem;
            cursor: pointer;
            color: #aaa;
        }
        
        .close:hover {
            color: #333;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: bold;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
        }
        
        .form-group textarea {
            height: 100px;
            resize: vertical;
        }
        
        .loading {
            text-align: center;
            padding: 2rem;
            color: #666;
        }
        
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            color: #666;
        }
        
        .empty-state h3 {
            margin-bottom: 1rem;
            color: #333;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }
            
            .toolbar {
                flex-direction: column;
                gap: 1rem;
            }
            
            .projects-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>📋 项目管理</h1>
            <p>管理您的学术研究项目</p>
        </div>
    </div>
    
    <div class="container">
        <div class="toolbar">
            <div>
                <a href="/" class="btn">← 返回首页</a>
            </div>
            <div>
                <button class="btn btn-success" onclick="showCreateProjectModal()">+ 创建新项目</button>
            </div>
        </div>
        
        <div id="projects-container">
            <div class="loading">
                <p>正在加载项目...</p>
            </div>
        </div>
    </div>
    
    <!-- 创建项目模态框 -->
    <div id="createProjectModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>创建新项目</h2>
                <span class="close" onclick="hideCreateProjectModal()">&times;</span>
            </div>
            <form id="createProjectForm">
                <div class="form-group">
                    <label for="projectTitle">项目标题 *</label>
                    <input type="text" id="projectTitle" name="title" required>
                </div>
                <div class="form-group">
                    <label for="projectDescription">项目描述</label>
                    <textarea id="projectDescription" name="description" placeholder="简要描述您的研究项目..."></textarea>
                </div>
                <div class="form-group">
                    <label for="researchArea">研究领域</label>
                    <select id="researchArea" name="research_area">
                        <option value="">请选择研究领域</option>
                        <option value="计算机科学">计算机科学</option>
                        <option value="人工智能">人工智能</option>
                        <option value="机器学习">机器学习</option>
                        <option value="数据科学">数据科学</option>
                        <option value="自然语言处理">自然语言处理</option>
                        <option value="计算机视觉">计算机视觉</option>
                        <option value="生物信息学">生物信息学</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="methodology">研究方法</label>
                    <select id="methodology" name="methodology">
                        <option value="">请选择研究方法</option>
                        <option value="实验研究">实验研究</option>
                        <option value="理论分析">理论分析</option>
                        <option value="文献综述">文献综述</option>
                        <option value="案例研究">案例研究</option>
                        <option value="调查研究">调查研究</option>
                        <option value="混合方法">混合方法</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="timeline">预期时长</label>
                    <select id="timeline" name="timeline">
                        <option value="">请选择时长</option>
                        <option value="3个月">3个月</option>
                        <option value="6个月">6个月</option>
                        <option value="12个月">12个月</option>
                        <option value="18个月">18个月</option>
                        <option value="24个月">24个月</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-success">创建项目</button>
                    <button type="button" class="btn" onclick="hideCreateProjectModal()">取消</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        let projects = [];
        
        // 页面加载时获取项目列表
        document.addEventListener('DOMContentLoaded', function() {
            loadProjects();
        });
        
        // 加载项目列表
        async function loadProjects() {
            try {
                const response = await fetch('/api/projects');
                const data = await response.json();
                
                if (data.success) {
                    projects = data.projects;
                    renderProjects();
                } else {
                    showError('加载项目失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        }
        
        // 渲染项目列表
        function renderProjects() {
            const container = document.getElementById('projects-container');
            
            if (projects.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <h3>还没有项目</h3>
                        <p>点击"创建新项目"开始您的第一个研究项目</p>
                        <button class="btn btn-success" onclick="showCreateProjectModal()">创建新项目</button>
                    </div>
                `;
                return;
            }
            
            const projectsHTML = projects.map(project => `
                <div class="project-card">
                    <div class="project-header">
                        <div>
                            <div class="project-title">${project.title}</div>
                            <div class="project-meta">
                                <span>📅 ${formatDate(project.created_at)}</span>
                                <span>🔬 ${project.research_area || '未指定'}</span>
                            </div>
                        </div>
                        <div class="project-status status-${project.status}">
                            ${getStatusText(project.status)}
                        </div>
                    </div>
                    
                    <div class="project-description">
                        ${project.description || '暂无描述'}
                    </div>
                    
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${project.progress}%"></div>
                    </div>
                    
                    <div class="project-meta">
                        <span>进度: ${project.progress.toFixed(1)}%</span>
                        <span>方法: ${project.methodology || '未指定'}</span>
                    </div>
                    
                    <div class="project-actions">
                        <a href="/project/${project.id}" class="btn btn-small">查看详情</a>
                        <button class="btn btn-small" onclick="generateResearchPlan('${project.id}')">生成计划</button>
                        <button class="btn btn-small" onclick="searchLiterature('${project.id}')">文献搜索</button>
                        <button class="btn btn-small" style="background: #dc3545;" onclick="deleteProject('${project.id}')">删除</button>
                    </div>
                </div>
            `).join('');
            
            container.innerHTML = `<div class="projects-grid">${projectsHTML}</div>`;
        }
        
        // 显示创建项目模态框
        function showCreateProjectModal() {
            document.getElementById('createProjectModal').style.display = 'block';
        }
        
        // 隐藏创建项目模态框
        function hideCreateProjectModal() {
            document.getElementById('createProjectModal').style.display = 'none';
            document.getElementById('createProjectForm').reset();
        }
        
        // 创建项目表单提交
        document.getElementById('createProjectForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const projectData = Object.fromEntries(formData.entries());
            
            try {
                const response = await fetch('/api/projects', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(projectData)
                });
                
                const data = await response.json();
                
                if (data.success) {
                    hideCreateProjectModal();
                    showSuccess('项目创建成功！');
                    loadProjects(); // 重新加载项目列表
                } else {
                    showError('项目创建失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        });
        
        // 生成研究计划
        async function generateResearchPlan(projectId) {
            try {
                showInfo('正在生成研究计划...');
                
                const response = await fetch(`/api/projects/${projectId}/research-plan`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({})
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('研究计划生成成功！');
                    // 可以在这里显示生成的计划详情
                    console.log('研究计划:', data.research_plan);
                } else {
                    showError('研究计划生成失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        }
        
        // 文献搜索
        async function searchLiterature(projectId) {
            const keywords = prompt('请输入搜索关键词（用逗号分隔）:');
            if (!keywords) return;
            
            try {
                showInfo('正在搜索文献...');
                
                const keywordList = keywords.split(',').map(k => k.trim());
                const response = await fetch('/api/literature/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        keywords: keywordList,
                        project_id: projectId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`搜索完成！找到 ${data.total_results} 篇相关文献`);
                    console.log('搜索结果:', data);
                } else {
                    showError('文献搜索失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        }
        
        // 工具函数
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        }
        
        function getStatusText(status) {
            const statusMap = {
                'planning': '规划中',
                'active': '进行中',
                'completed': '已完成',
                'paused': '已暂停'
            };
            return statusMap[status] || status;
        }
        
        function showSuccess(message) {
            alert('✅ ' + message);
        }
        
        function showError(message) {
            alert('❌ ' + message);
        }
        
        function showInfo(message) {
            alert('ℹ️ ' + message);
        }
        
        // 删除项目
        async function deleteProject(projectId) {
            if (!confirm('确定要删除这个项目吗？此操作不可撤销。')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/projects/${projectId}`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('项目删除成功！');
                    loadProjects(); // 重新加载项目列表
                } else {
                    showError(data.message || '项目删除失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('createProjectModal');
            if (event.target === modal) {
                hideCreateProjectModal();
            }
        }
    </script>
</body>
</html>